// 1. React核心库
import React, { useState, useEffect, useCallback, useRef } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, message, Modal, Space, Tag, Popconfirm } from 'antd';

// 3. 图标库
import { PlusOutlined, EditOutlined, DeleteOutlined, StarOutlined, MessageOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable, ProColumns, ActionType } from '@ant-design/pro-components';

// 5. 工具库
import dayjs from 'dayjs';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import FavoriteForm from './components/FavoriteForm';
import FavoriteDetail from './components/FavoriteDetail';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { UserFavorite } from '@/services/generated';

const UserFavoriteList: React.FC = () => {
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<UserFavorite | null>(null);
  const actionRef = useRef<ActionType>();

  // 数据获取函数
  const fetchData = async (params: any) => {
    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatFavoritesList({
        page: params.current,
        pageSize: params.pageSize,
        search: params.search,
      });
      return {
        data: response.data?.items || [],
        success: true,
        total: response.data?.total || 0,
      };
    } catch (error) {
      message.error('获取数据失败');
      return { data: [], success: false, total: 0 };
    }
  };

 
  // 删除收藏
  const handleDelete = useCallback(async (id: number) => {
    try {
      await autoLoginInDev();
      await apiClients.aiChat.aiChatFavoritesDestroy({ id: String(id) });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  }, []);

  // 跳转到对话
  const handleGoToConversation = useCallback((conversationId: number) => {
    // 跳转到聊天页面
    window.open(`/ai-chat/conversations/chat/${conversationId}`, '_blank');
  }, []);

  // 表格列定义
  const columns: ProColumns<UserFavorite>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '收藏标题',
      dataIndex: 'title',
      ellipsis: true,
      formItemProps: {
        rules: [{ required: true, message: '请输入收藏标题' }],
      },
    },
    {
      title: '对话标题',
      dataIndex: 'conversation_title',
      ellipsis: true,
      search: false,
    },
    {
      title: '备注',
      dataIndex: 'note',
      ellipsis: true,
      search: false,
      width: 200,
    },
    {
      title: '收藏时间',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
      sorter: true,
      render: (_, record) => {
        if (!record.created_at) return '-';
        const date = dayjs(record.created_at);
        return date.isValid() ? date.format('YYYY-MM-DD HH:mm') : '-';
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 240,
      render: (_, record) => [
        <Button
          key="goto"
          type="link"
          size="small"
          icon={<MessageOutlined />}
          onClick={() => handleGoToConversation(record.conversation!)}
        >
          查看对话
        </Button>,
        <Button
          key="detail"
          type="link"
          size="small"
          onClick={() => {
            setCurrentRecord(record);
            setDetailModalVisible(true);
          }}
        >
          详情
        </Button>,
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => {
            setCurrentRecord(record);
            setEditModalVisible(true);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除这个收藏吗？"
          onConfirm={() => handleDelete(record.id!)}
          okText="确定"
          cancelText="取消"
        >
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
          >
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '我的收藏',
        subTitle: '管理收藏的对话和消息',
      }}
    >
      <ProTable<UserFavorite>
           scroll={{x: 'max-content'}}
        headerTitle="收藏列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<StarOutlined />}
            onClick={() => setCreateModalVisible(true)}
          >
            新建收藏
          </Button>,
        ]}
        request={fetchData}
        columns={columns}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
        }}
      />

      {/* 新建收藏Modal */}
      <Modal
        title="新建收藏"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        width={600}
      >
        <FavoriteForm
          onSubmit={async (values) => {
            try {
              await autoLoginInDev();
              await apiClients.aiChat.aiChatFavoritesCreate({ userFavoriteRequest: values });
              message.success('创建成功');
              setCreateModalVisible(false);
              actionRef.current?.reload();
            } catch (error) {
              message.error('创建失败');
            }
          }}
          onCancel={() => setCreateModalVisible(false)}
        />
      </Modal>

      {/* 编辑收藏Modal */}
      <Modal
        title="编辑收藏"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
        width={600}
      >
        <FavoriteForm
          initialValues={currentRecord || undefined}
          onSubmit={async (values) => {
            try {
              await autoLoginInDev();
              await apiClients.aiChat.aiChatFavoritesUpdate({
                id: String(currentRecord!.id),
                userFavoriteRequest: values
              });
              message.success('更新成功');
              setEditModalVisible(false);
              setCurrentRecord(null);
              actionRef.current?.reload();
            } catch (error) {
              message.error('更新失败');
            }
          }}
          onCancel={() => {
            setEditModalVisible(false);
            setCurrentRecord(null);
          }}
        />
      </Modal>

      {/* 收藏详情Modal */}
      <Modal
        title="收藏详情"
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setCurrentRecord(null);
        }}
        footer={null}
        width={800}
      >
        <FavoriteDetail 
          favorite={currentRecord}
          onGoToConversation={handleGoToConversation}
        />
      </Modal>
    </PageContainer>
  );
};

export default UserFavoriteList;
